package cn.iocoder.yudao.module.team.service.orde;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.team.dal.dataobject.linetrip.LineTripDO;
import cn.iocoder.yudao.module.team.dal.mysql.linetrip.LineTripMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import cn.iocoder.yudao.module.team.controller.admin.orde.vo.*;
import cn.iocoder.yudao.module.team.dal.dataobject.orde.OrdeDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.team.dal.mysql.orde.OrdeMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.team.enums.ErrorCodeConstants.*;

/**
 * 团队订单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class OrdeServiceImpl implements OrdeService {

    @Resource
    private OrdeMapper ordeMapper;
    @Resource
    private LineTripMapper lineTripMapper;
    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有
    public Integer createOrde(OrdeSaveReqVO createReqVO) {
        // 插入
        OrdeDO orde = BeanUtils.toBean(createReqVO, OrdeDO.class);
        orde.setNumbers(danhao("sj"));
/*//查询库的最后一条
        OrdePageReqVO reqVO=new OrdePageReqVO();
        reqVO.setPageSize(1);
        LambdaQueryWrapperX<OrdeDO> lq=new LambdaQueryWrapperX<>();
        lq.orderByDesc(OrdeDO::getCreateTime);
        lq.last("LIMIT 1");
        OrdeDO ordeDO=ordeMapper.selectOne(lq);
        LocalDateTime c =  LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault());
        System.out.println("查询库的最后一条,"+ordeDO);
        System.out.println("当前时间,"+ordeDO);
        boolean is=isSameDay(ordeDO.getCreateTime(),System.currentTimeMillis());
        if (is){
            System.out.println("想等——————————————————,");
        }else {
            System.out.println("不等——————————————————,");
        }*/

        ordeMapper.insert(orde);
        //插入订单行程
        // 使用for循环设置id为2
        for (LineTripDO ent : createReqVO.getListLinTrip()) {
            ent.setColumn2(String.valueOf(orde.getId()));
        }
        lineTripMapper.insert(createReqVO.getListLinTrip());
        // 返回
        return orde.getId();
    }
    public static boolean isSameDay( LocalDateTime dateTime1, long timestamp2) {
        // 将时间戳转换为LocalDateTime
        //LocalDateTime dateTime1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp1), ZoneId.systemDefault());
        LocalDateTime dateTime2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp2), ZoneId.systemDefault());

        // 仅比较日期部分
        return dateTime1.toLocalDate().equals(dateTime2.toLocalDate());
    }
    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有
    public void updateOrde(OrdeSaveReqVO updateReqVO) {
        // 校验存在
        validateOrdeExists(updateReqVO.getId());
        //删除原有的团行程
        LambdaQueryWrapperX<LineTripDO> wrapper=new LambdaQueryWrapperX<LineTripDO>();
        wrapper.eq(LineTripDO::getColumn2,updateReqVO.getId());
        lineTripMapper.delete(wrapper);
        //在添加新的订单行程模板
        // 使用for循环设置id为2
        for (LineTripDO ent : updateReqVO.getListLinTrip()) {
            ent.setColumn2(String.valueOf(updateReqVO.getId()));
        }
        lineTripMapper.insert(updateReqVO.getListLinTrip());
        // 更新
        OrdeDO updateObj = BeanUtils.toBean(updateReqVO, OrdeDO.class);
        ordeMapper.updateById(updateObj);
    }
    //批量
    @Override
    public void updateBatch(List<OrdeDO> ordeDOlist) {
        ordeMapper.updateBatch(ordeDOlist);
    }
    @Override
    public void deleteOrde(Integer id) {
        // 校验存在
        validateOrdeExists(id);
        // 删除
        ordeMapper.deleteById(id);
    }

    @Override
        public void deleteOrdeListByIds(List<Integer> ids) {
        // 删除
        ordeMapper.deleteByIds(ids);
        }


    private void validateOrdeExists(Integer id) {
        if (ordeMapper.selectById(id) == null) {
            throw exception(ORDE_NOT_EXISTS);
        }
    }

    @Override
    public OrdeDO getOrde(Integer id) {
        return ordeMapper.selectById(id);
    }

    @Override
    public PageResult<OrdeDO> getOrdePage(OrdePageReqVO pageReqVO) {
        return ordeMapper.selectPage(pageReqVO);
    }
  public String danhao(String prefix){
      String noPrefix = prefix + DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN);
      //查询库的最后一条
      OrdePageReqVO reqVO=new OrdePageReqVO();
      reqVO.setPageSize(1);
      LambdaQueryWrapperX<OrdeDO> lq=new LambdaQueryWrapperX<>();
      lq.orderByDesc(OrdeDO::getCreateTime);
      lq.last("LIMIT 1");
      OrdeDO ordeDO=ordeMapper.selectOne(lq);

      if (ordeDO==null){
          return noPrefix+"aa";
      }
     // System.out.println("查询库的最后一条,"+ordeDO.getId()+":"+ordeDO.getCreateTime());
     // System.out.println("当前时间,"+ordeDO);
      boolean is=isSameDay(ordeDO.getCreateTime(),System.currentTimeMillis());
      String lastTwoChars = ordeDO.getNumbers().substring(ordeDO.getNumbers().length() - 2);
      //System.out.println("返回库最后的英文组合,"+lastTwoChars);
      if (is){
          String zuihou= nextCharPair(lastTwoChars);
          System.out.println("想等——————————————————,"+noPrefix+zuihou);
          return noPrefix+zuihou;
      }else {
          System.out.println("不等——————————————————,"+noPrefix+"aa");
          return noPrefix+"aa";
      }



  }
   //生成订单号aa
    public  String nextCharPair(String current) {
        if (current == null || current.length() != 2 || !isAlpha(current.charAt(0)) || !isAlpha(current.charAt(1))) {
            throw new IllegalArgumentException("Input must be a two-letter string where both letters are alphabetic.");
        }

        char first = current.charAt(0);
        char second = current.charAt(1);

        if (second == 'z') { // 如果第二个字符是'z'，则进位到'a'并增加第一个字符
            if (first == 'z') { // 如果已经是'zz'，则无法递增，返回null或抛出异常
                return null; // 或者 throw new IllegalArgumentException("Maximum value reached.");
            }
            second = 'a'; // 重置第二个字符为'a'
            first++; // 增加第一个字符的ASCII值
        } else { // 否则直接增加第二个字符的ASCII值
            second++; // 增加第二个字符的ASCII值
        }
        //String noPrefix = prefix + DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN);

        return String.valueOf(first) + second; // 返回新的字符串
    }

    private static boolean isAlpha(char c) { // 检查是否是字母的方法
        return (c >= 'a' && c <= 'z'); // 只检查小写字母，可根据需要扩展到大小写字母判断
    }

}